﻿using UnityEngine;
using Zero;

/// <summary>
/// 元素反应：冻结
/// </summary>
public class ElementFrozen : IElementReaction
{
    private readonly IElementHolder _holder;
    private readonly IElementAura _waterAura;
    private readonly IElementAura _iceAura;
    private readonly IElementAura _frozenAura;

    public ElementFrozen(IElementHolder holder)
    {
        _holder = holder;
        _waterAura = _holder.GetElementAura("水");
        _iceAura = _holder.GetElementAura("冰");
        _frozenAura = _holder.GetElementAura("冻结");
    }

    public void Reaction(TriggerElementData triggerElementData)
    {
        if (TrySyntheticFrozenGauge(triggerElementData, out var frozenGauge))
        {
            if (_frozenAura.Gauge > 0f)
            {
                _frozenAura.Source = triggerElementData.Source;
                _frozenAura.Gauge += frozenGauge;
            }
            else
            {
                ServiceLocator.Get<IWorldNumberService>()
                    .CreateElementReaction(_holder.Owner.transform.position, "冻结");
                _frozenAura.Attach(frozenGauge, triggerElementData.Source);
            }

            triggerElementData.IsTriggered = true;
        }
    }

    private bool TrySyntheticFrozenGauge(TriggerElementData triggerElementData, out float frozenGauge)
    {
        if (triggerElementData.ElementType == ElementType.Ice)
        {
            if (_waterAura.Gauge > 0f)
            {
                var minGauge = Mathf.Min(_waterAura.Gauge, triggerElementData.Gauge);
                _waterAura.Gauge -= minGauge;
                triggerElementData.Gauge -= minGauge;
                frozenGauge = 2f * minGauge;
                return true;
            }
        }

        if (triggerElementData.ElementType == ElementType.Water)
        {
            if (_iceAura.Gauge > 0f)
            {
                var minGauge = Mathf.Min(_iceAura.Gauge, triggerElementData.Gauge);
                _iceAura.Gauge -= minGauge;
                triggerElementData.Gauge -= minGauge;
                frozenGauge = 2f * minGauge;
                return true;
            }
        }

        frozenGauge = 0f;
        return false;
    }
}